package com.example.servicetest

import android.app.Service
import android.content.Intent
import android.media.AudioAttributes
import android.media.MediaPlayer
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.annotation.RequiresApi

/**
 * 播放音乐的对象
 */
class MusicService : Service() {
    private val TAG = "MusicService"
    private var player:MediaPlayer?=null
    override fun onBind(intent: Intent): IBinder {
        TODO("Return the communication channel to the service.")
    }

    /**
     * 不仅要使当前的音乐退出 而且还要使应用退出
     */
    private fun exitMusic() {
//        TODO("Not yet implemented")
        stopMusic()

    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.e(TAG, "onStartCommand: " )
        val action = intent!!.getStringExtra("action")
        Log.e(TAG, "onStartCommand: $action" )
        when(action){
            "play"->play()
            "pause"->pauseMusic()
            "stop"->stopMusic()
            "exit"->exitMusic()
        }
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        super.onDestroy()
        stopMusic()
    }

    private fun stopMusic() {
//        TODO("Not yet implemented")
        if (player!=null){
            this.player!!.stop()
            this.player!!.reset()
            this.player!!.release()
            this.player=null
        }
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    private fun play() {
//        TODO("Not yet implemented")
        Log.e(TAG, "play: " )
        if (this.player==null){
            this.player= MediaPlayer.create(this,R.raw.luomeizhuang,
                    AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build(),1)

        }
        player!!.start()
    }

    private fun pauseMusic() {
//        TODO("Not yet implemented")
        if(this.player!!.isPlaying){
            this.player!!.pause()
        }
    }

    private fun initMediaPlayer(){
        var assetManager=assets
        val fd = assetManager.openFd("luomeizhuang.mp3")

    }
}